package cn.emailChat.ai.repo;

import cn.emailChat.ai.common.enums.MessageStatusType;
import cn.emailChat.ai.domain.MessageStatus;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

/**
 * @Description 用于消息状态表的持久化、查询及更新
 * @Author susu
 * @Date 2025/8/18
 */
public interface MessageStatusRepo extends JpaRepository<MessageStatus, Long> {

    Optional<MessageStatus> findByMessageId(String messageId);

    // 给重试任务用
    List<MessageStatus> findByStatusAndRetryCountLessThanOrderByUpdateTimeAsc(
            MessageStatusType status, int retryCount, Pageable pageable
    );

    long deleteByStatusAndUpdateTimeBefore(MessageStatusType status, LocalDateTime cutoff);

    @Query("""
        select ms
        from MessageStatus ms
        where (:messageId is null or ms.messageId = :messageId)
          and (:status is null or ms.status = :status)
          and (:minRetry is null or ms.retryCount >= :minRetry)
          and (:maxRetry is null or ms.retryCount <= :maxRetry)
          and (:startTime is null or ms.updateTime >= :startTime)
          and (:endTime is null or ms.updateTime < :endTime)
        order by ms.updateTime desc
    """)
    Page<MessageStatus> findByQuery(
            @Param("messageId") String messageId,
            @Param("status") MessageStatusType status,
            @Param("minRetry") Integer minRetry,
            @Param("maxRetry") Integer maxRetry,
            @Param("startTime") LocalDateTime startTime,
            @Param("endTime") LocalDateTime endTime,
            Pageable pageable
    );
}
